<template>
    <base-table-layout
      title="植保管理"
      :total="total"
      :current-page="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      @update:currentPage="val => searchForm.pageNum = val"
      @update:pageSize="val => searchForm.pageSize = val"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 搜索区域 -->
      <template #search>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <div class="search-form-row">
            <el-form-item label="农户姓名">
              <el-input
                v-model="searchForm.growerName"
                placeholder="农户姓名"
                style="width: 200px"
                @keyup.enter.native="handleSearch"
              />
            </el-form-item>
            <el-form-item label="所属部门">
              <dept-tree-select
                v-model="searchForm.deptId"
                placeholder="选择部门"
                width="250px"
                @change="handleSearch"
              />
            </el-form-item>
          </div>
          <div class="search-form-row">
            <el-form-item label="植保时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 350px"
                value-format="yyyy-MM-dd"
                @change="handleDateChange"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px">
                <el-option label="全部" :value="undefined" />
                <el-option label="已打药" :value="1" />
                <el-option label="未打药" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <div class="button-group">
                <el-button type="primary" icon="el-icon-search" @click="handleSearch" class="form-button">搜索</el-button>
                <el-button type="info" icon="el-icon-refresh" @click="resetSearch" class="form-button">重置</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </template>
  
      <!-- 操作区域 -->
      <template #operation>
        <div class="operation-buttons">
          <el-button type="primary" icon="el-icon-download" @click="exportExcel" class="operation-button">导出Excel</el-button>
        </div>
      </template>
  
      <!-- 表格区域 -->
      <template #table>
        <el-table
          v-loading="loading"
          :data="pestControlList"
          border
          style="width: 100%"
        >
          <el-table-column prop="recordId" label="记录ID" width="80" />
          <el-table-column prop="growerName" label="农户姓名" min-width="100" />
          <el-table-column prop="phone" label="联系电话" min-width="120" />
          <el-table-column label="所属区域" min-width="200">
            <template slot-scope="scope">
              {{ scope.row.villageGroupName }}
            </template>
          </el-table-column>
          <el-table-column prop="controlTime" label="植保时间" width="180" />
          <el-table-column prop="area" label="面积(亩)" width="100" align="right">
            <template slot-scope="scope">
              {{ scope.row.area || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <div class="operation-btn-group">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleViewMedia(scope.row)"
                  icon="el-icon-picture"
                >图片</el-button>
                <el-button
                  size="mini"
                  type="warning"
                  @click="handleEdit(scope.row)"
                  icon="el-icon-edit"
                >修改</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
  
      <!-- 弹窗区域 -->
      <template #dialogs>
        <!-- 图片查看弹窗 -->
        <el-dialog
          title="图片记录"
          :visible.sync="mediaDialogVisible"
          width="80%"
          :close-on-click-modal="false"
        >
          <div v-if="mediaList.length === 0" class="no-media">
            <el-empty description="暂无图片记录"></el-empty>
          </div>
          <div v-else class="media-container">
            <div v-for="(item, index) in mediaList" :key="index" class="media-item">
              <!-- 根据媒体类型显示图片或视频 -->
              <el-image 
                v-if="item.mediaType === 1"
                :src="item.mediaUrl" 
                :preview-src-list="getImagePreviewList()"
                fit="cover"
                class="media-image"
              />
              <video 
                v-else-if="item.mediaType === 2" 
                :src="item.mediaUrl" 
                controls
                class="media-video"
              ></video>
              <div class="media-info">
                <p><strong>类型:</strong> {{ getRecordTypeText(item.recordType) }}</p>
                <p><strong>媒体:</strong> {{ getMediaTypeText(item.mediaType) }}</p>
                <p v-if="item.remark"><strong>备注:</strong> {{ item.remark }}</p>
                <p v-if="item.longitude && item.latitude"><strong>经纬度:</strong> {{ item.longitude }}, {{ item.latitude }}</p>
                <p><strong>地理位置:</strong> {{ item.locationDesc || '未知' }}</p>
                <p><strong>上传时间:</strong> {{ formatDateTime(item.uploadTime) }}</p>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <div class="dialog-button-group">
              <el-button @click="mediaDialogVisible = false" class="dialog-button">关闭</el-button>
              <el-button type="primary" @click="handleUploadMedia" class="dialog-button">上传图片</el-button>
            </div>
          </div>
        </el-dialog>
  
        <!-- 修改面积对话框 -->
        <el-dialog
          title="修改植保面积"
          :visible.sync="editDialogVisible"
          width="500px"
          :close-on-click-modal="false"
        >
          <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
            <el-form-item label="面积(亩)" prop="newArea">
              <el-input-number
                v-model="editForm.newArea"
                :min="0"
                :precision="1"
                :step="0.5"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <div class="dialog-button-group">
              <el-button @click="editDialogVisible = false" class="dialog-button">取 消</el-button>
              <el-button type="primary" @click="submitEditForm" class="dialog-button">确 定</el-button>
            </div>
          </div>
        </el-dialog>
      </template>
    </base-table-layout>
  </template>
  
  <script>
  import request from '@/utils/request'
  import _ from 'lodash'
  import * as XLSX from 'xlsx'
  import BaseTableLayout from '@/components/BaseTableLayout.vue'
  import DeptTreeSelect from '@/components/DeptTreeSelect.vue'
  
  export default {
    name: 'PestControlManager',
    components: {
      BaseTableLayout,
      DeptTreeSelect
    },
    data() {
      return {
        loading: false,
        searchForm: {
          pageNum: 1,
          pageSize: 10,
          growerName: '',
          deptId: undefined,
          startTime: undefined,
          endTime: undefined,
          status: undefined
        },
        dateRange: [],
        pestControlList: [],
        total: 0,
        
        // 媒体查看相关
        mediaDialogVisible: false,
        currentRecordId: null,
        mediaList: [],
        
        // 修改面积相关
        editDialogVisible: false,
        editForm: {
          recordId: undefined,
          newArea: undefined
        },
        editRules: {
          newArea: [{ required: true, message: '请输入植保面积', trigger: 'blur' }]
        }
      }
    },
    computed: {
      mediaUrls() {
        return this.mediaList.map(item => item.mediaUrl)
      }
    },
    created() {
      this.fetchPestControlList()
    },
    methods: {
      // 获取植保记录列表
      async fetchPestControlList() {
        try {
          this.loading = true
          const params = {
            pageNum: this.searchForm.pageNum,
            pageSize: this.searchForm.pageSize,
            growerName: this.searchForm.growerName || undefined,
            deptId: this.searchForm.deptId,
            startTime: this.searchForm.startTime,
            endTime: this.searchForm.endTime,
            status: this.searchForm.status
          }
          const response = await request.get('/pest-control/page', { params })
          if (response) {
            this.pestControlList = response.records || []
            this.total = response.total || 0
            this.searchForm.pageSize = response.size || 10
            this.searchForm.pageNum = response.current || 1
          }
        } catch (error) {
          console.error('获取植保记录失败:', error)
          this.$message.error('获取植保记录失败')
        } finally {
          this.loading = false
        }
      },
  
      handleSearch: _.debounce(function() {
        this.searchForm.pageNum = 1
        this.fetchPestControlList()
      }, 300),
  
      resetSearch() {
        this.searchForm = {
          pageNum: 1,
          pageSize: 10,
          growerName: '',
          deptId: undefined,
          startTime: undefined,
          endTime: undefined,
          status: undefined
        }
        this.dateRange = []
        this.handleSearch()
      },
  
      handleSizeChange(val) {
        this.searchForm.pageSize = val
        this.fetchPestControlList()
      },
  
      handleCurrentChange(val) {
        this.searchForm.pageNum = val
        this.fetchPestControlList()
      },
  
      handleDateChange(val) {
        if (val) {
          // 添加时间部分，以符合后端要求的格式
          this.searchForm.startTime = val[0] + ' 00:00:00'
          this.searchForm.endTime = val[1] + ' 23:59:59'
        } else {
          this.searchForm.startTime = undefined
          this.searchForm.endTime = undefined
        }
      },
  
      // 获取状态类型
      getStatusType(status) {
        const statusMap = {
          1: 'success',   // 已打药
          2: 'info'       // 未打药
        }
        return statusMap[status] || 'info'
      },
  
      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          1: '已打药',
          2: '未打药'
        }
        return statusMap[status] || '未知'
      },
      
      // 查看媒体
      async handleViewMedia(row) {
        try {
          this.loading = true
          this.currentRecordId = row.recordId
          
          const response = await request.get('/file/list', {
            params: {
              recordType: 2, // 植保记录
              recordId: row.recordId
            }
          })
          
          this.mediaList = response || []
          this.mediaDialogVisible = true
        } catch (error) {
          console.error('获取媒体记录失败:', error)
          this.$message.error('获取媒体记录失败')
        } finally {
          this.loading = false
        }
      },
      
      // 上传媒体
      handleUploadMedia() {
        // 这里需要集成文件上传功能
        this.$message.info('此功能需要集成文件上传组件')
      },
  
      // 导出Excel
      async exportExcel() {
        try {
          this.loading = true
          // 使用较大的pageSize以获取更多数据
          const exportParams = {
            pageNum: 1,
            pageSize: 10000, // 使用大的分页大小
            growerName: this.searchForm.growerName || undefined,
            deptId: this.searchForm.deptId,
            startTime: this.searchForm.startTime,
            endTime: this.searchForm.endTime,
            status: this.searchForm.status
          }
          
          // 获取数据
          const response = await request.get('/pest-control/page', { params: exportParams })
          if (!response || !response.records) {
            this.$message.warning('没有数据可导出')
            this.loading = false
            return
          }
          
          const exportData = response.records
          if (exportData.length === 0) {
            this.$message.warning('没有数据可导出')
            this.loading = false
            return
          }
          
          // 准备导出数据
          const excelData = exportData.map(item => {
            return {
              '记录ID': item.recordId,
              '农户姓名': item.growerName,
              '联系电话': item.phone,
              '烟站': item.tobaccoStationName,
              '乡镇': item.townName,
              '村组': item.villageGroupName,
              '植保时间': item.controlTime || '',
              '面积(亩)': item.area || '',
              '状态': this.getStatusText(item.status),
              '备注': item.remark || ''
            }
          })
          
          // 设置列的顺序
          const header = ['记录ID', '农户姓名', '联系电话', '烟站', '乡镇', '村组', '植保时间', '面积(亩)', '状态', '备注']
          
          // 创建工作表
          const worksheet = XLSX.utils.json_to_sheet(excelData, {
            header: header
          })
          
          // 设置列宽
          const colWidth = [
            { wch: 10 },  // 记录ID
            { wch: 15 },  // 农户姓名
            { wch: 15 },  // 联系电话
            { wch: 15 },  // 烟站
            { wch: 15 },  // 乡镇
            { wch: 20 },  // 村组
            { wch: 20 },  // 植保时间
            { wch: 10 },  // 面积
            { wch: 10 },  // 状态
            { wch: 30 }   // 备注
          ]
          worksheet['!cols'] = colWidth
          
          // 创建工作簿并添加工作表
          const workbook = XLSX.utils.book_new()
          XLSX.utils.book_append_sheet(workbook, worksheet, '植保记录')
          
          // 获取当前时间作为文件名的一部分
          const now = new Date()
          const dateString = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`
          const fileName = `植保记录_${dateString}.xlsx`
          
          // 导出工作簿
          XLSX.writeFile(workbook, fileName)
          this.$message.success('导出成功')
        } catch (error) {
          console.error('导出Excel失败:', error)
          this.$message.error('导出Excel失败: ' + (error.message || '未知错误'))
        } finally {
          this.loading = false
        }
      },
  
      getRecordTypeText(recordType) {
        const recordTypeMap = {
          1: '移栽记录',
          2: '植保记录'
        }
        return recordTypeMap[recordType] || '未知记录'
      },
      
      // 获取媒体类型文本
      getMediaTypeText(mediaType) {
        const mediaTypeMap = {
          1: '图片',
          2: '视频'
        }
        return mediaTypeMap[mediaType] || '未知类型'
      },

      // 获取图片预览列表
      getImagePreviewList() {
        return this.mediaList
          .filter(item => item.mediaType === 1)
          .map(item => item.mediaUrl)
      },

      formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';
        return dateTimeStr.replace('T', ' ');
      },

      // 修改面积
      handleEdit(row) {
        this.editForm = {
          recordId: row.recordId,
          newArea: row.area || undefined
        }
        this.editDialogVisible = true
      },
      
      // 提交修改面积表单
      async submitEditForm() {
        try {
          await this.$refs.editForm.validate()
          
          await request.put(`/pest-control/${this.editForm.recordId}?newArea=${this.editForm.newArea}`)
          this.$message.success('修改面积成功')
          
          this.editDialogVisible = false
          this.fetchPestControlList()
        } catch (error) {
          console.error('修改面积失败:', error)
          this.$message.error(error.response?.data?.msg || '修改面积失败')
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .dialog-footer {
    text-align: right;
    
    .dialog-button-group {
      display: inline-flex;
      gap: 10px;
    }
  }
  
  .search-form {
    .el-form-item {
      margin-bottom: 10px;
      margin-right: 10px;
    }
    
    .search-form-row {
      display: flex;
      flex-wrap: wrap;
      align-items: flex-start;
      margin-bottom: 5px;
    }
    
    .form-button {
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .button-group {
      display: flex;
      gap: 10px;
    }
  }
  
  .operation-buttons {
    display: flex;
    gap: 10px;
  }
  
  .operation-button {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .table-button {
    height: 28px;
    padding: 5px 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
  
  .dialog-button {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .media-container {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }
  
  .media-item {
    width: 300px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .media-image,
  .media-video {
    width: 100%;
    height: 200px;
    object-fit: cover;
  }
  
  .media-info {
    padding: 10px;
    
    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;
    }
  }
  
  .no-media {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
  }
  
  .operation-btn-group {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .el-table .el-button+.el-button {
    margin-left: 0;
  }
  
  .el-table .el-button {
    padding: 7px 10px;
  }
  </style>